package vault

import (
	"fmt"
	"gitee.com/git_public/vfaith/builtin/bean"
	"gitee.com/git_public/vfaith/builtin/shape"
	"gitee.com/git_public/vfaith/sugar"
	"strconv"
	"strings"
)

//region 结构体定义

type SqlCondition struct {
	Conditions []string
	Args       []interface{}
}

type QueryParam struct {
	*PageCondition
	entityParam  bean.IxBaseEntityDTO
	conditions   *shape.Map
	orderBy      string
	groupBy      string
	sqlCondition *SqlCondition
}

func NewSearchEntity(dtoEntity bean.IxBaseEntityDTO) *QueryParam {
	param := NewQueryParam(false)
	param.SetEntityParam(dtoEntity)

	return param
}

func NewQueryParam(isPage bool, args ...*shape.Map) *QueryParam {
	argsMap := shape.GetDefaultMap(args)

	var pageCondition *PageCondition
	if isPage {
		pageCondition = NewPageCondition(argsMap)
		//} else {
		//	pageCondition = new(PageCondition)
	}

	queryParam := &QueryParam{
		PageCondition: pageCondition,
		conditions:    argsMap,
		orderBy:       "",
		groupBy:       "",
		sqlCondition:  new(SqlCondition),
	}

	return queryParam
}

func GetDefaultQueryParam(args []*QueryParam) *QueryParam {
	return sugar.GetDefaultArgs(args, func() *QueryParam {
		return NewQueryParam(true)
	})
}

//endregion

//region 结构体方法

func (param *QueryParam) SetEntityParam(params bean.IxBaseEntityDTO) {
	param.entityParam = params
}

func (param *QueryParam) SetOrderBy(orderBy string) {
	param.orderBy = orderBy
}

func (param *QueryParam) SetGroupBy(groupBy string) {
	param.groupBy = groupBy
}

//endregion

//region 获取结构体私有属性

func (param *QueryParam) Conditions() *shape.Map {
	return param.conditions
}

func (param *QueryParam) GetParam(keyToFind string) any {
	v, ok := param.conditions.Get(keyToFind)
	if ok {
		return v
	}
	return nil
}

func (param *QueryParam) EntityParam() bean.IxBaseEntityDTO {
	return param.entityParam
}

func (param *QueryParam) OrderBy() string {
	return param.orderBy
}

func (param *QueryParam) GroupBy() string {
	return param.groupBy
}

func (param *QueryParam) SqlCondition() *SqlCondition {
	return param.sqlCondition
}

//endregion

//region 构建SQL查询条件

func (param *QueryParam) AddParam(k string, v any) error {
	condition := param.conditions
	if condition == nil {
		return fmt.Errorf("QueryParam:Condition未初始化")
	}
	if condition.Add(k, v) {
		return nil
	}
	return fmt.Errorf("QueryParam:未知错误或插入Condition已存在")
}

func (param *QueryParam) AddCondition(condition string, args any, handleType ...string) error {

	sc := param.sqlCondition

	sc.Conditions = append(sc.Conditions, condition)

	// 检测是否有传参valueType
	if input, ok := args.(string); ok && len(handleType) > 0 {
		switch handleType[0] {
		case "split":
			// 将字符串分割为子字符串切片
			parts := strings.Split(input, ",")
			// 将每个子字符串转换为整数并存储在 args 中
			for _, part := range parts {
				num, err := strconv.Atoi(part)
				if err != nil {
					return err
				}
				//args[i] = num
				sc.Args = append(sc.Args, num)
			}
		}
	} else if args == nil {
	} else {
		sc.Args = append(sc.Args, args)
	}
	return nil
}

func GetParam[T any](param *QueryParam, keyToFind string) (T, bool) {
	v, _ := param.conditions.Get(keyToFind)
	if v != nil {
		return v.(T), true
	}

	// 如果没有找到匹配项，返回类型 T 的零值
	var zeroValue T
	return zeroValue, false
}

// SpiltReplace 根据数量替换【?】占位符
func SpiltReplace(condition, input string) string {

	// 将字符串分割为子字符串切片
	parts := strings.Split(input, ",")

	// 创建占位符字符串
	placeholders := strings.Repeat("?,", len(parts))
	placeholders = placeholders[:len(placeholders)-1] // 移除最后一个逗号
	placeholders = fmt.Sprintf(condition, placeholders)

	return placeholders
}

//endregion

//region 冗余方法

func toInt(input string) (int, error) {

	if input == "" {
		return 0, fmt.Errorf("input parameter is empty")
	}

	paramInt, err := strconv.Atoi(input)
	if err != nil {
		return 0, fmt.Errorf("input parameter '%s' is invalid: %v", input, err)
	}

	return paramInt, nil
}

//endregion
